import Request from "luch-request";
import jwt from "../auth/jwt"

const http = new Request();
const baseURL = "http://takeaway.com/api/v1";

http.interceptors.request.use(async (config) => { // 可使用async await 做异步操作
    config.baseURL = baseURL;
    config.header = {
        ...config.header,
        "Content-Type": "application/json;charset=UTF-8",
    }
    // 演示custom 用处
    if (config.custom.auth) {
        config.header.Authorization = jwt.getAccessToken();
    }
    if (config.custom.loading) {
        uni.showLoading()
    }
    return config
}, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
});

http.interceptors.response.use(async (response) => {

    //如果是需要权限认证的路由
    if (response.config.custom.auth) {
        if (response.data.code == 4011) {
            //刷新token
            jwt.setAccessToken(response.data.data.access_token);
            //携带新 token 重新请求
            let repeatRes = await http.request(response.config);
            if (repeatRes) {
                response = repeatRes;
            }
        }
    }

    return response

}, (response) => {
    /*  对响应错误做点什么 （statusCode !== 200）*/
    console.log(response)
    return Promise.reject(response)
});

export {
    http
}